package arithmetic.thread.sync007;

import groovy.json.JsonOutput;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicUse {

    @Data
    class User{
        String name;
        String age;
        public User(String name,String age){
            this.age=age;
            this.name=name;
        }

    }

    private static AtomicInteger count = new AtomicInteger(0);

    //多个addAndGet在一个方法内是非原子性的，需要加synchronized进行修饰，保证4个addAndGet整体原子性

    /**
     * synchronized
     */
    public synchronized int multiAdd() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count.addAndGet(1);
        count.addAndGet(2);
        count.addAndGet(3);
        count.addAndGet(4); //+10
        return count.get();
    }


    public static void main(String[] args) {

        final AtomicUse au = new AtomicUse();

        List<Thread> ts = new ArrayList<Thread>();
        for (int i = 0; i < 100; i++) {
            ts.add(new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(au.multiAdd());
                }
            }));
        }

        for (Thread t : ts) {
            t.start();
        }

    }

    @Test
    public void test(){
        User zhangsan = new User("zhangsan", "213");
        User lisi = new User("lisi", "213");

        AtomicReference atomicReference =  new AtomicReference();
        atomicReference.set(zhangsan);
        System.out.println(atomicReference.compareAndSet(zhangsan,lisi)+" " + atomicReference.get().toString());
        System.out.println(atomicReference.compareAndSet(zhangsan,lisi)+" " + JsonOutput.toJson(atomicReference.get()));

    }
}
